package cn.gongwebo.payview.temp;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;

import cn.gongwebo.payview.R;

/**
 * Created by GongWenBo on 2017/12/13.
 */

public class ProgressView extends View {

    private Paint   mPaint;
    private Context mContext;
    private float   mRadius;
    private float   progress;
    // 背景的颜色
    private int color_bg       = Color.parseColor("#DFDFDF");
    // 文字的颜色
    private int color_text     = Color.parseColor("#ffffff");
    // 进度条的颜色
    private int color_progress = Color.parseColor("#52A8FC");

    public ProgressView(Context context) {
        this(context, null);
    }

    public ProgressView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
        mContext = context;
    }

    private void init(Context context) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(context.getResources().getColor(R.color.gray));
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        mRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, dm);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        setMeasuredDimension(width, height);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int mWidth = getWidth();
        int mHeight = getHeight();
        float width = progress / 100 * mWidth;
        mPaint.setColor(color_bg);
        canvas.drawRoundRect(0, 0, mWidth, mHeight, mRadius, mRadius, mPaint);
        if (progress != 0) {
            mPaint.setColor(color_progress);
            canvas.drawRoundRect(0, 0, width, mHeight, mRadius, mRadius, mPaint);
        }
        // 画文字
        mPaint.setColor(color_text);
        mPaint.setTextSize(24);
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        // 保证竖直居中
        int baseline = (int) ((0 + mHeight - fontMetrics.bottom - fontMetrics.top) / 2);
        // 保证水平居中
        mPaint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText(((int) progress) + "%", mWidth / 2, baseline, mPaint);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void setProgress(float progress) {
        this.progress = progress;
        postInvalidate();
    }

}
